package com.mtech.modbus_rtu.codec.impl;

import com.mtech.modbus_rtu.codec.ModbusRTUDecoder;
import com.mtech.modbus_rtu.codec.ModbusRTUEncoder;
import com.mtech.modbus_rtu.data._03.MultiReadRxDataGram;
import com.mtech.modbus_rtu.data._03.MultiReadTxDataGram;
import com.mtech.modbus_rtu.data._06.OneWriteRxDataGram;
import com.mtech.modbus_rtu.data._06.OneWriteTxDataGram;
import com.mtech.modbus_rtu.data._10.MultiWriteRxDataGram;
import com.mtech.modbus_rtu.data._10.MultiWriteTxDataGram;
import com.mtech.modbus_rtu.data.base.ModbusDataGram;

/**
 * 统一编码解码器
 * 
 * @author lixiaolong
 * @CreateDate 2018年3月19日
 */
public class ModbusRTUCodec implements ModbusRTUDecoder<ModbusDataGram>, ModbusRTUEncoder<ModbusDataGram> {

	private ModbusRTUCodec() {

	}

	/**
	 * 获取实例
	 * 
	 * @Author lixiaolong
	 * @CreateDate
	 * @return
	 */
	public static ModbusRTUCodec getInstance() {
		return new ModbusRTUCodec();
	}

	@Override
	public byte[] encode(ModbusDataGram data) {
		return data.toBytes();
	}

	@Override
	public ModbusDataGram decodeTx(byte[] buf) {
		byte funCode = buf[1];
		switch (funCode) {
		case 0x03: {
			return new MultiReadTxDataGram(buf);
		}
		case 0x06: {
			return new OneWriteTxDataGram(buf);
		}
		case 0x10: {
			return new MultiWriteTxDataGram(buf);
		}
		default: {
			throw new RuntimeException("该功能码[" + funCode + "]不存在");
		}
		}
	}

	@Override
	public ModbusDataGram decodeRx(byte[] buf) {
		byte funCode = buf[1];
		switch (funCode) {
		case 0x03: {
			return new MultiReadRxDataGram(buf);
		}
		case 0x06: {
			return new OneWriteRxDataGram(buf);
		}
		case 0x10: {
			return new MultiWriteRxDataGram(buf);
		}
		default: {
			throw new RuntimeException("该功能码[" + funCode + "]不存在");
		}
		}
	}

}
